package wzvtc.dbad.attend;

import org.h2.tools.Server;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import javax.sql.DataSource;
import java.sql.SQLException;

@Configuration
public class H2ServerStartConfig {



    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;

    @Value("${spring.datasource.password}")
    private String password;

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.url}")
    private String url;




    @Bean
    @DependsOn("h2server")
    @ConfigurationProperties(prefix = "application")
    public DataSource dataSource() {

        //EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
        DataSourceBuilder builder= DataSourceBuilder.create();
        builder.url(url).password(password).username(username).driverClassName(driverClassName);
        return builder.build();

        //return builder.setType(EmbeddedDatabaseType.H2).build();
    }


    // @Bean(initMethod = "start", destroyMethod = "stop")
    @Order(Ordered.HIGHEST_PRECEDENCE)

    @Bean(name="h2server",destroyMethod = "stop")
    public Server h2Server() throws SQLException {
        //  return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", "9092");

        Server retVal = null;


        final String userDir = System.getProperty("user.dir");
        System.setProperty("h2.baseDir", userDir + "/data/");

        retVal = Server.createTcpServer("-baseDir", userDir+"/data/","-tcp", "-tcpAllowOthers", "-tcpPort", "9093","-ifNotExists");

        retVal.start();

        return retVal;
    }

}
